# coding=utf-8
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views import View
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse

from recite.models import *
from recite.forms import *
from recite.utils import *

# Create your views here.


@login_required()
def main(request):
    try:
        user = LevelUser.get_user(user=request.user)
        # 需要复习的单词数量
        review_count = ListUser.get_review_word_count(request.user)
        if review_count >= user.nums:
            new_count = 0
        else:
            new_count = user.nums - review_count
        # 得到学习单词的列表
        word_list = ListUser.get_recite_word(request.user, review_count, new_count, user.level)

        request.session['word_list'] = word_list
        request.session['review_list'] = {}

        context = {'review': review_count, 'new': new_count}
        return render(request, 'recite/index.html', context)
    except ObjectDoesNotExist:
        return HttpResponseRedirect(reverse('set_profile'))


class SetUserProfileView(View):
    template_name = 'recite/set_user_profile.html'
    error_template = 'accounts/error.html'
    self_url = '/accounts/login/?next=/recite/set_profile/'

    def get(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('user_login'))

        word_level = WordLevel.objects.all()
        return render(request, self.template_name, {'word_level': word_level})

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('user_login'))

        user_level = request.POST.copy()
        user_level['user'] = request.user.id

        try:
            # 已经存在的用户需要更新
            exist_user = LevelUser.objects.get(user=request.user.id)
            form = LevelUserForm(user_level, instance=exist_user)
        except ObjectDoesNotExist:
            form = LevelUserForm(user_level)

        if form.is_valid():
            form.save()
            # 设置完成后开始背单词
            return HttpResponseRedirect(reverse('main'))
        else:
            errors = form.errors.as_json()
            return render(request, self.error_template, {'errors': errors})


class ReciteWordView(View):
    template_name = 'recite/recite.html'
    login_url = '/accounts/login/'
    self_url = '/recite/recite/'
    detail_url = '/recite/detail/'

    current_id = 0
    word_id = None

    def get(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('user_login'))

        recite_logger(request)

        # 下一个单词
        action = kwargs.get('action')
        if action == 'next':
            self.set_current_next(request)
            return HttpResponseRedirect(reverse('recite'))

        self.get_current_word(request)

        # 单词顺序为按照id从小到大开始，包括复习的单词总是比新学的单词id小
        # 当条件出发一次后，session的值一直存在
        if self.current_id + 1 == len(request.session.get('word_list')):
            self.get_review_word(request)
            request.session['review'] = 1

        current_word = WordList.get_by_id(self.word_id)

        context = {'word': current_word}
        return render(request, self.template_name, context)

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('user_login'))

        type = request.POST.get('type')
        review = request.session.get('review', 0)
        self.get_current_word(request)

        if type == '1':
            # 已经背会的单词
            ListUser.learned_word(request.user, self.word_id)

            if review == '1':
                # 来自今天复习的单词背会了需要从待复习列表中删除
                request.session['review_list'].pop(self.current_id)
            return HttpResponseRedirect(reverse('detail'))
        else:
            # 不会的单词需要在此记录
            request.session['review_list'][str(self.current_id)] = self.word_id
            return HttpResponseRedirect(reverse('detail'))

    def get_current_word(self, request):
        self.current_id = request.session.get('current_id', 0)
        self.word_id = request.session.get('word_list')[self.current_id]
        return True

    def get_review_word(self, request):
        self.current_id = request.session.get('review_id', 0)
        self.word_id = request.session.get('review_list')[self.current_id]
        return True

    def set_current_next(self, request):
        """如果今天的单词还没学完，下一个就是今天单词列表内的下一个，否则从复习列表中获取一个"""
        review = request.session.get('review', 0)
        if review == 0:
            current_id = request.session.get('current_id', 0)
            request.session['current_id'] = current_id + 1
        else:
            print(request.session.get('review_list'))
            k, _ = request.session['review_list'].items()[0]
            request.session['current_id'] = k
        return True


class DetailWordView(View):
    template_name = 'recite/detail.html'
    self_url = '/recite/detail/'
    error_template = 'accounts/error.html'

    current_id = 0
    word_id = None

    def get(self, request):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('user_login'))

        recite_logger(request)

        self.get_current_word(request)
        # 得到单词基本信息
        word = WordList.get_by_id(self.word_id)
        # 得到单词系统例句
        word_example = WordExample.get_word_examples(word)
        # 得到用户创建的例句
        word_user_example = WordExample.get_word_examples(word, request.user)
        # 得到单词共享例句
        word_share_example = WordExample.get_word_share_example(word)
        # 得到单词用户笔记
        word_user_notes = WordNotes.get_word_notes(word, request.user)
        # 得到单词共享笔记
        word_share_notes = WordNotes.get_word_share_notes(word)

        context = {
            'word': word,
            'word_example': word_example,
            'word_user_example': word_user_example,
            'word_share_example': word_share_example,
            'word_user_notes': word_user_notes,
            'word_share_notes': word_share_notes,
        }
        return render(request, self.template_name, context)

    def get_current_word(self, request):
        self.current_id = request.session.get('current_id', 0)
        self.word_id = request.session.get('word_list')[self.current_id]
        return True

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('user_login'))

        from_input = request.POST.get('from')
        self.get_current_word(request)

        user_data = request.POST.copy()
        user_data['user'] = request.user.id
        user_data['word'] = self.word_id

        if from_input == 'example':
            form = WordExampleForm(user_data)
        else:
            form = WordNotesForm(user_data)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('detail'))
        else:
            errors = form.errors.as_json()
            return render(request, self.error_template, {'errors': errors})
